package com.example.maax.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.toolkit.ChainWrappers;
import com.example.maax.entity.Device;
import com.example.maax.mapper.DeviceMapper;
import com.example.maax.mapper.UserMapper;
import com.example.maax.vo.DeviceQueryDTO;
import com.example.maax.vo.DeviceReqVO;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

@RestController
@RequestMapping("/device")
@RequiredArgsConstructor
public class DeviceController {
    private final DeviceMapper deviceMapper;

    @GetMapping
    public Object list(DeviceQueryDTO queryDTO) {
        ChainWrappers.lambdaQueryChain(deviceMapper)
                .eq(StringUtils.hasText(queryDTO.getUserId()), Device::getUserId, queryDTO.getUserId())
                .list();
        return JSON.toJSONString(deviceMapper.selectList(null));
    }

    @PostMapping
    public void create(@RequestBody DeviceReqVO reqVO) {
        if (ChainWrappers.lambdaQueryChain(deviceMapper)
                .eq(Device::getCode, reqVO.getCode())
                .eq(Device::getUserId, reqVO.getUserId())
                .exists()) {
            throw new ResponseStatusException(400, "code重复", null);
        }

        deviceMapper.insert(DeviceReqVO.convert(reqVO));
    }

    @PutMapping("/{id}")
    public void update(@PathVariable Long id, @RequestBody DeviceReqVO reqVO) {
        if (ChainWrappers.lambdaQueryChain(deviceMapper)
                .eq(Device::getCode, reqVO.getCode())
                .eq(Device::getUserId, reqVO.getUserId())
                .ne(Device::getId, id)
                .exists()) {
            throw new ResponseStatusException(400, "code重复", null);
        }

        Device device = DeviceReqVO.convert(reqVO);
        device.setId(id);
        deviceMapper.updateById(device);
    }

    @DeleteMapping("/{code}")
    public void delete(@PathVariable String code) {
        ChainWrappers.lambdaUpdateChain(deviceMapper)
                .eq(Device::getCode, code)
                .remove();
    }
}
